<template>
  <div class="policy-statistics-root app-container">
    <list-page-container>
      <template slot="query">
        <el-form :model="tableQueryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="保单所属组织" prop="areaCode">
            <el-cascader
                placeholder="请选择保单所属组织"
                @change="setCurrentAreaNameAndQueryData"
                v-model="tableQueryParams.areaCode"
                :options="areaData"
                :props="{ checkStrictly: true,label:'orgName',value:'orgCode' }"
                clearable></el-cascader>
          </el-form-item>
          <el-form-item label="保单所属年份" prop="orderYear">
            <el-date-picker
                @change="handleQuery"
                v-model="tableQueryParams.orderYear"
                value-format="yyyy"
                type="year"
                placeholder="选择年">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" prop="keyword">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>
      </template>

      <template slot="table">
        <el-descriptions class="descriptions-root margin-top margin-bottom" :title="currentAreaName" :column="3"
                         border>

          <el-descriptions-item labelClassName="labelClassName"
                                v-for="(item, index) in statisticalChartConfiguration.filter(item => item.baseTitle != null)"
                                :key="item.containerId">
            <template slot="label">
              <i class="el-icon-user"></i>
              {{ item.baseTitle }}
            </template>
            {{ item.sumData }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="chart-root">

          <div class="chart-item" v-for="(item, index) in statisticalChartConfiguration" :key="item.containerId">
            <div class="chart-title">
              {{ item.title }}
            </div>
            <div class="chart-container" :id="item.containerId"></div>
          </div>
        </div>
      </template>
    </list-page-container>
  </div>
</template>

<script>
import {listPageMixins} from "@/mixins/listPageMixins";
import {getAreaData} from "@/utils/getAreaData";
import {isArr} from "@/utils/arrayUtil";
import {extractTwoLevels} from "@/utils/baseUtil";
import guid from "@/utils/guid";
import {Chart} from '@antv/g2';
import {statisticalApi} from "@/api/statistical";

export default {
  name: "index",

  data() {
    const BAR = 'bar';
    const PIE = 'pie'
    return {
      BAR,
      PIE,
      // 查询参数
      tableQueryParams: {
        // 所属地域
        areaCode: ['152223'],
        // 所属年份(也加在列表上)
        orderYear: '2023',
      },
      areaData: [],
      statisticalChartConfiguration: [
        {
          queryUrl: '/insuranceOrder/orderManager/statisticZbf',
          showType: BAR,
          containerId: `bar_${guid()}`,
          title: '统计各子级行政区划保费(元)',
          baseTitle: '总保费(元)',
          sumData: 0
        },
        {
          queryUrl: '/insuranceOrder/orderManager/statisticOrderCount',
          showType: BAR,
          containerId: `bar_${guid()}`,
          title: '统计各子级行政区划保单数量(个)',
          baseTitle: '总行政区划保单数量(个)',
          sumData: 0
        },
        {
          queryUrl: '/insuranceOrder/orderManager/statisticCzmj',
          showType: BAR,
          containerId: `bar_${guid()}`,
          title: '统计各灾害类型成灾面积(平方米)',
          baseTitle: '总灾害类型成灾面积(平方米)',
          sumData: 0
        },
        {
          queryUrl: '/insuranceOrder/orderManager/statisticLpmj',
          showType: BAR,
          containerId: `bar_${guid()}`,
          title: '统计各行政区划保险公司理赔面积(平方米)',
          baseTitle: '总保险公司理赔面积(平方米)',
          sumData: 0
        },
        {
          queryUrl: '/insuranceOrder/orderManager/statisticLpmjWithZhdj',
          showType: BAR,
          containerId: `bar_${guid()}`,
          title: '统计各受灾等级保险公司理赔面积(平方米)'
        }
      ],
      currentAreaName: '扎赉特旗',
      baseAreaData: []
    }
  },
  methods: {
    setCurrentAreaNameAndQueryData(value) {
      const lastAreaCode = value.at(-1)
      this.currentAreaName = this.baseAreaData.find(item => item.orgCode === lastAreaCode)?.orgName
      this.handleQuery()
    },
    updateQueryParams(params) {
      let resultParams = _.cloneDeep(params)
      if (isArr(resultParams?.areaCode)) {
        resultParams.areaCode = params.areaCode.at(-1)
      }
      return resultParams
    },
    async initAreaData() {
      let {threeData, baseData} = await getAreaData();
      this.baseAreaData = baseData
      this.areaData = extractTwoLevels(threeData);
    },
    getStatisticalChartData() {
      this.startLoading()
      let [owner, {statisticalChartConfiguration, tableQueryParams, BAR, PIE}] = [this, this]
      const queryParam = this.updateQueryParams(tableQueryParams)
      this.$nextTick(async () => {
        let chartDatas = await Promise.all(statisticalChartConfiguration.map(configItem => statisticalApi(configItem.queryUrl, queryParam)))
        chartDatas = chartDatas.map(item => item.data)
        chartDatas.forEach(chartData => {
          chartData = chartData.map(dataItem => {
            dataItem.value = parseFloat(dataItem.value)
            return dataItem
          })
        })

        owner.computeCurrentAreaData(chartDatas)
        for (const configItem of statisticalChartConfiguration) {
          const configIndex = statisticalChartConfiguration.indexOf(configItem);
          let {showType, containerId: container} = configItem
          let chart = new Chart({
            container,
            autoFit: true,
          });
          switch (showType) {
            case BAR:
              chart = owner.barHandle(chart, chartDatas[configIndex])
              break;
            case PIE:
              chart = owner.pieHandle(chart, chartDatas[configIndex])
          }
          chart.render();
          owner.endLoading()
        }
      })
    },
    computeCurrentAreaData(chartDatas) {
      this.statisticalChartConfiguration = this.statisticalChartConfiguration.map((configItem, configIndex) => {
        configItem.sumData = chartDatas[configIndex].map(dataItem => dataItem.value).reduce((pre, cur) => pre + cur).toFixed(2)
        return configItem
      })
    },
    barHandle(chart, data) {
      const xName = data[0].parentLabel != null && data[0].parentLabel != '' ? 'parentLabel' : 'label'
      chart.interval().data(data).encode('x', xName).encode('y', 'value').encode('color', 'label').slider('x', {}).legend(false).axis({
        y: {title: ''},
        x: {title: ''}
      }).interaction('tooltip', {
        // render 回调方法返回一个innerHTML 或者 ReactNode
        render: (event, item) => {
          let {label, value} = data.find(dataItem => dataItem.value === item.items[0].value)
          return `${label} : ${value}`
        },
      })
      // chart.text()
      return chart
    },
    pieHandle(chart, data) {
      chart.coordinate({type: 'theta', innerRadius: 0.6});
      chart.interval()
          .data(data)
          .transform({type: 'stackY'})
          .encode('y', 'value')
          .encode('color', 'label')
          .style('stroke', 'white')
          .style('inset', 1)
          .style('radius', 10)
          .scale('color', {
            palette: 'spectral',
            offset: (t) => t * 0.8 + 0.1,
          })
          .label({text: 'label', fontSize: 10, fontWeight: 'bold'})
          .label({
            text: 'value',
            fontSize: 9,
            dy: 12,
          })
          .animate('enter', {type: 'waveIn'})
          .legend(false);

      return chart
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.tableQueryParams.pageNum = 1;
      this.getStatisticalChartData();
    },
  },
  async created() {
    await this.initAreaData()
    this.getStatisticalChartData()
  },
  mounted() {
  }
}
</script>

<style scoped lang="scss">
::v-deep .descriptions-root {
  width: 100% !important;
  margin-bottom: 20px !important;

  .labelClassName {
    width: 300px !important;
  }
}

.chart-root {
  height: calc(100% - 200px);
  width: 100%;
  overflow: auto;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  box-sizing: border-box;


  .chart-item {
    height: 500px;
    width: 33%;
    margin-bottom: 30px;

    .chart-title {
      width: 100%;
      margin-bottom: 16px;
      text-align: center;
      color: #101424;
      font-size: 16px;
      line-height: 22px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-weight: 600;
    }

    .chart-container {
      width: 100%;
      height: calc(100% - 38px);
    }
  }
}
</style>
